#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <list>
#include <thread>
#include <mutex>
using namespace std;

list<sockaddr_in *> cli_addrs;
mutex addr_mutex;

bool find_addr(sockaddr_in *addr)
{
    unique_lock<mutex> lock(addr_mutex);
    bool exist = false;
    for(const auto &d : cli_addrs) {
        if(addr->sin_addr.s_addr == d->sin_addr.s_addr && addr->sin_port == addr->sin_port)
            return true;
    }
    return false;
}

void insert_addr(sockaddr_in *addr)
{
    if(!find_addr(addr)) {
        unique_lock<mutex> lock(addr_mutex);
        cli_addrs.push_back(addr);
    }
}

void release_addr()
{
    unique_lock<mutex> lock(addr_mutex);
    while(cli_addrs.size() > 0) {        
        auto d = cli_addrs.back();
        delete d;
        d = nullptr;
        cli_addrs.pop_back();
    }
}

void recv_thread(int fd)
{
    char buf[1024] = {};
    while(1) {
        memset(buf, 0, 1024);
        sockaddr_in *cli_addr = new sockaddr_in;
        memset(cli_addr, 0, sizeof(*cli_addr));
        socklen_t cli_len = sizeof(*cli_addr);
        int len = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)cli_addr, &cli_len);
        insert_addr(cli_addr);
        if(len == -1) {
            perror("recv failed");
        }
        else {
            printf("[%d] %s\n", len, buf);
        }      
    }
}

void send_thread(int fd)
{
    char buf[1024] = {};
    while(1) {
        memset(buf, 0, 1024);
        cout << "输入消息：";
        cin.getline(buf, 1024);
        if(strlen(buf) == 0)
            continue;
        if(strcmp(buf, "quit") == 0)
            exit(0);
        bool exist = false;
        unique_lock<mutex> lock(addr_mutex);
        for(const auto &d : cli_addrs) {
            int len = sendto(fd, buf, strlen(buf) + 1, 0, (struct sockaddr*)d, sizeof(*d));
            if(len == -1) {
                perror("send failed");
            }
        }
    }
}

int main()
{
    // 1. 创建 soclet 连接
    int serfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(serfd == -1) {
        perror("create socket failed");
        return 0;
    }
    else {
        cout << "create socket successful\n";
    }

    // 2. 绑定 IP 地址和端口号
    struct sockaddr_in server_sockaddr;
    server_sockaddr.sin_family = AF_INET;//TCP/IP协议族
    server_sockaddr.sin_port = htons(8000);//端口号
    server_sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int ret = bind(serfd, (struct sockaddr *)&server_sockaddr, sizeof(server_sockaddr));
    if(ret == -1) {
        perror("bind failed");
        close(serfd);
        return 0;
    }

    // 3. 发送/接收消息
    thread t_recv(recv_thread, serfd), t_send(send_thread, serfd);
    t_recv.join();
    t_send.join();


    release_addr();
    // 4. 关闭 socket 连接
    close(serfd);

    return 0;
}